/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.lizg.View;

import cn.lizg.Controller.MessReceive;
import cn.lizg.Controller.MessSend;
import cn.lizg.Model.Send;
import cn.lizg.util.UiUtil;
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 *
 * @author LizG
 */
public class Send_JFr extends javax.swing.JFrame {

    /**
     * Creates new form Send_JFr
     */
    private static String ip;
    private static Send send;
    private Thread thread;
    boolean flag = true;
    public Send_JFr() {
        initComponents();
        UiUtil.setFrameCenter(this);
        UiUtil.setFrameImage(this);
        send = new Send(ip);
    }

    public void setIp(String ip) {
        this.ip = ip;
        System.out.println("传来的ip是" + this.ip);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        log_jTA = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        sendpath_jTF = new javax.swing.JTextField();
        chooser_jBt = new javax.swing.JButton();
        send_jBt = new javax.swing.JButton();
        trans_jBt = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        log_jTA.setEditable(false);
        log_jTA.setColumns(20);
        log_jTA.setRows(5);

        jLabel1.setText("log：");

        sendpath_jTF.setEditable(false);
        sendpath_jTF.setText("选择的路径");

        chooser_jBt.setText("选择文件...");
        chooser_jBt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chooser_jBtActionPerformed(evt);
            }
        });

        send_jBt.setText("确认发送");
        send_jBt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                send_jBtActionPerformed(evt);
            }
        });

        trans_jBt.setText("转为接收");
        trans_jBt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                trans_jBtActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(log_jTA, javax.swing.GroupLayout.PREFERRED_SIZE, 304, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(sendpath_jTF, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(chooser_jBt, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(send_jBt)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(trans_jBt, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(131, 131, 131))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(4, 4, 4)
                .addComponent(log_jTA, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sendpath_jTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chooser_jBt)
                    .addComponent(send_jBt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 110, Short.MAX_VALUE)
                .addComponent(trans_jBt, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void chooser_jBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooser_jBtActionPerformed
      // TODO add your handling code here:
        JFileChooser jfc = new JFileChooser();
        String AbsolutePath = null;
        jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        jfc.showDialog(new JLabel(), "选择");
        File file = jfc.getSelectedFile();
        if (file.isDirectory()) {
            // System.out.println("文件夹:"+file.getAbsolutePath());  
            AbsolutePath = file.getAbsolutePath();
        } else if (file.isFile()) {
            //System.out.println("文件:"+file.getAbsolutePath());  
            AbsolutePath = file.getAbsolutePath();
        }

        this.sendpath_jTF.setText(AbsolutePath);
        send.setFile(AbsolutePath);
    }//GEN-LAST:event_chooser_jBtActionPerformed

    private void send_jBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_send_jBtActionPerformed
       // TODO add your handling code here:
        this.flag = true;
        if (this.sendpath_jTF.getText().trim().equals("选择的路径")) {
            JOptionPane.showMessageDialog(this, "未选择文件");
        } else {
            if(flag){
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    MessReceive messReceive = new MessReceive();
                    //messReceive.setIp("192.168.1.114");//
                    System.out.println("启动send方的接收UDP");
                    messReceive.receiveMess();
                    System.out.println("接收mess完成");
                    if(messReceive.getMess().equals("@receive")){
                        System.out.println("开始发送文件");
                        send.send();//开始发送文件
                    }
                }
            });
            if(!thread.isAlive()){
                thread.start();
            }
            flag = false;
            }
            MessSend ms = new MessSend();
            String[] filenames = this.sendpath_jTF.getText().trim().split("\\\\");
            String filename = filenames[filenames.length-1];
            ms.setFilename(filename);
            ms.setIp_receive(ip);
            System.out.println("发送信息去receive方  ip:" + ip);
            ms.sendMess();
        }
    }//GEN-LAST:event_send_jBtActionPerformed

    private void trans_jBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_trans_jBtActionPerformed
        // TODO add your handling code here:
        GetIP_JFr getIP_JFr = new GetIP_JFr();
        getIP_JFr.setGetIP_JFr(true);
        UiUtil.setFrameappearence();
        System.gc();
        this.dispose();
    }//GEN-LAST:event_trans_jBtActionPerformed

    /**
     * @param flag
     */
    public void setSend_JFrV(boolean flag) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Enter_JFr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Enter_JFr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Enter_JFr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Enter_JFr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new Send_JFr().setVisible(flag);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton chooser_jBt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextArea log_jTA;
    private javax.swing.JButton send_jBt;
    private javax.swing.JTextField sendpath_jTF;
    private javax.swing.JButton trans_jBt;
    // End of variables declaration//GEN-END:variables
}
